package com.jweb.framework.security.data.safe;

import com.jweb.framework.security.crypto.cipher.symmetric.DefaultSymCipherer;
import com.jweb.framework.security.crypto.cipher.symmetric.SymCipherer;
import com.jweb.framework.security.crypto.common.ECipherMode;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：对部分字段加密处理
 */
public class DataFieldEncrypt implements IEncrypt {
	
	final byte initKeyBytes[] = {101, 111, 33, -117, -51, -85, 9, 120};

	@Override
	public byte[] getEncrypt(String in , String pwd) {
		
		byte[] enBytes = this.getEncryptBytes(in.getBytes(), pwd);
		return enBytes ;
	}

	@Override
	public String getEncryptStr(String in , String pwd) {
		
		byte[] bytes = this.getEncrypt(in, pwd);
		
		return bcd2asc(bytes);
	}
	
	public byte[] getEncryptBytes(byte[] sourceBytes , String pwd) {
		SymCipherer encrypter = new DefaultSymCipherer(ECipherMode.ENCRYPT);
		byte[] pwdByte = pwd.getBytes();
		byte[] pwds = new byte[]{0 , 0 , 0 , 0 , 0 , 0 , 0 , 0};
		if(pwdByte.length > 8){
			System.arraycopy(pwdByte , 0 , pwds , 0 , 8);
		}
		else if(pwdByte.length < 8){
			System.arraycopy(pwdByte , 0 , pwds , 0 , pwdByte.length);
		}
		else {
			System.arraycopy(pwdByte , 0 , pwds , 0 , 8);
		}
		
		byte[] enBytes = encrypter.encrypt(this.initKeyBytes , pwds , sourceBytes);
		
		return enBytes ;
	}
	
	private String bcd2asc(byte b[]){
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			/**
			 * toHexString(int i)：以十六进制(基数16)无符号整数形式返回一个整数参数的字符串表示形式。
			 */
			stmp = Integer.toHexString(b[n] & 255);
			if (stmp.length() == 1)
				hs = (new StringBuilder(String.valueOf(hs))).append("0").append(stmp).toString();
			else
				hs = (new StringBuilder(String.valueOf(hs))).append(stmp).toString();
		}
		return hs.toUpperCase();
	}

}
